<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
    <link rel="icon" type="image/png" href="./favicon.png" />
    <title>Login | Zoraxy</title>
    <link rel="stylesheet" href="script/semantic/semantic.min.css">
    <link href="script/aos.css" rel="stylesheet">
    <script src="script/aos.js"></script>
    <script type="application/javascript" src="script/jquery-3.6.0.min.js"></script>
    <script type="application/javascript" src="script/semantic/semantic.min.js"></script>
    <style>
        body {
            background: rgb(231, 231, 231);
        }

        /* Time based background */
        body.morning{
            background: rgb(171,199,255);
            background: linear-gradient(48deg, rgba(171,199,255,1) 21%, rgba(193,227,255,1) 79%); 
        }

        body.afternoon{
            background: rgb(108,172,255);
            background: linear-gradient(21deg, rgba(108,172,255,1) 21%, rgba(141,235,255,1) 79%); 
        }

        body.evening{
            background: rgb(247,143,173);
            background: linear-gradient(21deg, rgba(247,143,173,1) 21%, rgba(253,235,130,1) 79%); 
        }

        body.night{
            background: rgb(18,19,23);
            background: linear-gradient(48deg, rgba(18,19,23,1) 21%, rgba(50,59,66,1) 79%); 
        }

        #errmsg{
            color: #9f3a38;
            margin-top: 1em;
            margin-bottom: 0.4em;
            text-align: left;
        }

        .registerOnly{
            display:none;
        }

        .ui.fluid.button.registerOnly{
            display:none;
        }

        #loginForm {
                border-radius: 1em;
                width: 25em;
                height: 450px;
                position: absolute; /*Can also be `fixed`*/
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
                /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
                max-width: 100%;
                max-height: 100%;
                overflow: auto;
                background-color: white;
        }

        .wavebase {
            position:fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height:5vh;
            text-align:center;
            padding-top: 1em;
            background-color: white;
        }

        /* 
            Waves CSS 
        */

        #wavesWrapper{
            position: fixed;
            bottom: 5vh;
            width: 100%;
            left: 0;
        }
        
        .waves {
            position:relative;
            width: 100%;
            height:15vh;
            margin-bottom:-7px; /*Fix for safari gap*/
            min-height:100px;
            max-height:150px;
        }

        
        .parallax > use {
            animation: move-forever 25s cubic-bezier(.55,.5,.45,.5)     infinite;
        }
        .parallax > use:nth-child(1) {
            animation-delay: -8s;
            animation-duration: 28s;
        }
        .parallax > use:nth-child(2) {
            animation-delay: -12s;
            animation-duration: 40s;
        }
        .parallax > use:nth-child(3) {
            animation-delay: -16s;
            animation-duration: 52s;
        }
        .parallax > use:nth-child(4) {
            animation-delay: -20s;
            animation-duration: 80s;
        }
        @keyframes move-forever {
            0% {
                transform: translate3d(-90px,0,0);
            }
            100% { 
                transform: translate3d(85px,0,0);
            }
        }
        /*Shrinking for mobile*/
        @media (max-width: 768px) {
            .waves {
                height:40px;
                min-height:40px;
            }
        }
        
    </style>
    </head>
    <body>
        <script>
            $(document).ready(function() {
                var currentHour = new Date().getHours();
                if (currentHour >= 5 && currentHour < 12) {
                    $("body").addClass("morning");
                } else if (currentHour >= 12 && currentHour < 17) {
                    $("body").addClass("afternoon");
                } else if (currentHour >= 17 && currentHour < 20) {
                    $("body").addClass("evening");
                } else {
                    $("body").addClass("night");
                }
            });
        </script>
        <div id="loginForm" class="ui middle aligned center aligned grid" data-aos="fade-up">
            <div class="column" style="padding-top: 0 !important;">
                <form class="ui large form content">
                    <div class="ui basic segment">
                        <img class="ui fluid image" src="img/public/logo.svg" style="pointer-events:none;">
                        <p class="registerOnly">Account Setup</p>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                <input id="username" type="text" name="username" placeholder="Username">
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                <input id="magic" type="password" name="password" placeholder="Password">
                            </div>
                        </div>
                        <div class="field registerOnly">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                <input id="repeatMagic" type="password" name="passwordconfirm" placeholder="Confirm Password" >
                            </div>
                        </div>
                        <div class="field loginOnly" style="text-align: left;">
                            <div class="ui checkbox">
                            <input id="rmbme" type="checkbox" tabindex="0" class="hidden">
                            <label>Remember Me</label>
                            </div>
                        </div>
                        <div id="loginbtn" class="ui fluid basic button loginOnly"> <i class="ui blue sign-in icon"></i> Login</div>
                        <div id="regsiterbtn" class="ui fluid basic button registerOnly"><i class="ui green checkmark icon"></i> Confirm</div>
                        <div id="errmsg"></div>
                        <div id="forgetPassword" class="field loginOnly" style="text-align: right; margin-top: 2em;">
                            <a href="#" onclick="sendResetAccountEmail();">Forget Password</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div id="wavesWrapper">
            <!-- CSS waves-->
            <svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
                <defs>
                <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
                </defs>
                <g class="parallax">
                <use xlink:href="#gentle-wave" x="48" y="0" fill="rgba(255,255,255,0.7" />
                <use xlink:href="#gentle-wave" x="48" y="3" fill="rgba(255,255,255,0.5)" />
                <use xlink:href="#gentle-wave" x="48" y="5" fill="rgba(255,255,255,0.3)" />
                <use xlink:href="#gentle-wave" x="48" y="7" fill="#fff" />
                </g>
            </svg>
        </div>
        <div class="wavebase">
            <p>Proudly powered by <a href="https://zoraxy.aroz.org" target="_blank">Zoraxy</a></p>
        </div>
    <script>
        AOS.init();
        var registerMode = false;
        var redirectionAddress = "/";
        var loginAddress = "/api/auth/login";
        $(".checkbox").checkbox();
        $(document).ready(function(){
            var currentdate = new Date(); 
            var datetime = currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();
            $("#requestTime").text(datetime);

            //Check if this is a new system
            $.get("/api/auth/userCount", function(data){
                if (data == 0){
                    //Allow user creation
                    registerMode = true;
                    $(".loginOnly").hide();
                    $(".registerOnly").show();
                }
            });
            //Check if the user already logged in
            $.get("/api/auth/checkLogin",function(data){
                try{
                    if (data === true || data.trim() == "true"){
                    //User already logged in. Redirect to target page.
                    if (redirectionAddress == ""){
                        //Redirect back to index
                        window.location.href = "/";
                    }else{
                        console.log(data);
                        //window.location.href = redirectionAddress;
                    }
                }
                }catch(ex){
                    //Assume not logged in
                    console.log(data);
                }
                
            });
            
        });

        function updateYear() {
            const year = new Date().getFullYear();
            const elements = document.getElementsByClassName("year");
            for (let i = 0; i < elements.length; i++) {
                elements[i].textContent = year;
            }
        }
        updateYear();

        //Event handlers for buttons
        $("#loginbtn").on("click",function(){
            login();
        });

        $("input").on("keydown",function(event){
            if (event.keyCode === 13) {
                event.preventDefault();
                if (registerMode){
                    //Register mode
                    if ($(this).attr("id") == "repeatMagic"){
                        $("#regsiterbtn").click();
                    }else{
                        //Focus to next field
                        $(this).next().focus();
                    }
                }else{
                    //Login mode
                    if ($(this).attr("id") == "magic"){
                        login();
                    }else{
                        //Fuocus to password field
                        $("#magic").focus();
                    }
                }
            }
        });

        $("#regsiterbtn").on("click", function(event){
            let username = $("#username").val();
            let magic = $("#magic").val();
            let repeatMagic = $("#repeatMagic").val();
            let csrfToken = document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content");
            if (magic !== repeatMagic) {
                alert("Password does not match");
                return;
            }

            $.ajax({
                url: "/api/auth/register",
                method: "POST",
                beforeSend: function(request) {
                    request.setRequestHeader("X-CSRF-Token",csrfToken);
                },
                data: {
                    username: username,
                    password: magic
                },
                success: function(data) {
                    if (data.error != undefined){
                        alert(data.error);
                    }else{
                        //Register success. Refresh page
                        window.location.reload();
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Error registering user:", error);
                }
            });
        });

        //Send account reset email to preset admin account  
        function sendResetAccountEmail(){
            $("#forgetPassword").html(`<i class="ui loading spinner icon"></i> Sending Email`);
            $("#forgetPassword").css("opacity", "0.8");
            $.get("/api/account/reset", function(data){
                if (data.error !== undefined){
                    $("#forgetPassword").html(`<a href="#" onclick="sendResetAccountEmail();">Forget Password</a>`);
                    alert(data.error);
                }else{
                    window.location.href = "/web/reset.html"
                }
            });
        }


        //Login system with the given username and password
        function login(){
            let username = $("#username").val();
            let magic = $("#magic").val();
            let rmbme = document.getElementById("rmbme").checked;
            let csrfToken = document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content");
            $("#errmsg").stop().finish().slideUp("fast");
            $("input").addClass('disabled');
            $.ajax({
                url: loginAddress, 
                type: "POST",
                beforeSend: function(request) {
                    request.setRequestHeader("X-CSRF-Token",csrfToken);
                },
                data: {
                    "username": username, 
                    "password": magic, 
                    "rmbme": rmbme,
                },
                success: function(data){
                    if (data.error !== undefined){
                        //Something went wrong during the login
                        $("#errmsg").html(`<i class="red remove icon"></i> ${data.error}`);
                        $("#errmsg").stop().finish().slideDown('fast');
                    }else if(data.redirect !== undefined){
                        //LDAP Related Code
                        window.location.href = data.redirect;
                    }else{
                        //Login succeed
                        if (redirectionAddress == ""){
                            //Redirect back to index
                            window.location.href = "./";
                        }else{
                            window.location.href = redirectionAddress;
                        }
                    }
                    $("input").removeClass('disabled');
                },
                error: function(){
                    alert("Something went wrong.")
                }
            });

        }

        function get(name){
            if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
                return decodeURIComponent(name[1]);
        }

        $(".thisyear").text(new Date().getFullYear());

        function updateRenderElements(){
            if (window.innerHeight < 520){
                $(".bottombar").hide();
            }else{
                $(".bottombar").show();
            }
        }
        updateRenderElements();
        $(window).on("resize", function(){
            updateRenderElements();
        });
    </script>
    </body>
</html>